import axios from 'axios'
import Vue from 'vue'
import router from '../router'

const http = axios.create({
  baseURL: 'http://127.0.0.1:8000'
})

http.interceptors.request.use(function (config) {
  config.headers.Authorization = 'Bearer ' + window.localStorage.getItem('token')
  return config
}, function (error) {
  return Promise.reject(error)
})

http.interceptors.response.use(function (response) {
  if (response.data.message) {
    Vue.prototype.$message({
      type: 'success',
      message: response.data.message
    })
  }
  return response.data
}, function (error) {
  Vue.prototype.$message({
    type: 'error',
    message: error.response.data.message
  })
  if (error.response.data.error !== -1) {
    router.push('/login')
  }
  return Promise.reject(error)
})

export default http
